<template>
  <div ref="editorDiffRef" class="monaco-editor" :style="'height: ' + height + ';'"></div>
</template>

<script setup lang="ts">
import prettier from 'prettier/standalone';
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import prettierPluginBabel from 'prettier/plugins/babel';
import prettierPluginEstree from 'prettier/plugins/estree';
defineOptions({
  name: 'DwDiffEditor',
});

// 类型注解
let editor: monaco.editor.IStandaloneDiffEditor | undefined;
let originalModel: monaco.editor.ITextModel | undefined;
let modifiedModel: monaco.editor.ITextModel | undefined;
const editorDiffRef = ref();

// 定义从父组件接收的属性
const props = defineProps({
  height: {
    type: String,
    default: '100%',
  },
  originalValue: {
    type: String,
  },
  modifiedValue: {
    type: String,
  },
});
const toFormatLanuage = async (value: string, parser: string) => {
  try {
    const code = await prettier.format(value, {
      parser: parser,
      plugins: [prettierPluginBabel, prettierPluginEstree], // 根据需要添加
      semi: true,
      trailingComma: 'all',
      singleQuote: true,
      printWidth: 80,
      tabWidth: 2,
    });
    return code;
  } catch (error) {
    console.error('Error formatting code:', error);
  }
};

const init = async () => {
  editor = monaco.editor.createDiffEditor(editorDiffRef.value, {
    fontSize: 14, // 字体大小
    theme: 'vs-dark', //主题
    readOnly: false, // 是否只读
    overviewRulerBorder: false, // 滚动是否有边框
    cursorSmoothCaretAnimation: 'on', // 控制光标平滑动画的开启与关闭。当开启时，光标移动会有平滑的动画效果。
    mouseWheelZoom: true, //设置是否开启鼠标滚轮缩放功能
    folding: true, //控制是否开启代码折叠功能
    automaticLayout: true, // 控制编辑器是否自动调整布局以适应容器大小的变化
    minimap: {
      enabled: false, // 是否启用预览图
    },
    scrollbar: {
      verticalScrollbarSize: 2, // 垂直滚动条宽度，默认px
      horizontalScrollbarSize: 2, // 水平滚动条高度
    },
    wordWrap: 'on', // 开启自动换行
    roundedSelection: true, // 右侧不显示编辑器预览框
    originalEditable: false, // 是否允许修改原始文本
  });

  // 创建左右编辑器
  originalModel = monaco.editor.createModel(props.originalValue ?? '', 'json');
  modifiedModel = monaco.editor.createModel(props.modifiedValue ?? '', 'json');
  editor?.setModel({
    original: originalModel,
    modified: modifiedModel,
  });
  editor.onDidChangeModel(() => {});
};

// 组件挂载后创建编辑器实例
onMounted(async () => {
  // 初始化编辑器
  await init();
});

// 组件卸载前销毁编辑器实例
onBeforeUnmount(() => {
  if (editor) {
    editor.dispose();
  }
});

watch(
  () => props.originalValue,
  (newValue) => {
    if (newValue) {
      if (editor) {
        toFormatLanuage(newValue || '{}', 'json').then((code) => {
          originalModel = monaco.editor.createModel(code || '', 'json');
          editor?.setModel({
            original: originalModel,
            modified: modifiedModel!,
          });
        });
      }
    }
  },
  { deep: true },
);

// 监听 value 的变化
watch(
  () => props.modifiedValue,
  (newValue) => {
    if (newValue) {
      if (editor) {
        toFormatLanuage(newValue || '{}', 'json').then((code) => {
          modifiedModel = monaco.editor.createModel(code || '', 'json');
          editor?.setModel({
            original: originalModel!,
            modified: modifiedModel,
          });
        });
      }
    }
  },
  { deep: true },
);
</script>

<style scoped>
.monaco-editor {
  width: 100%;
}
</style>
